﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace ZP.Common
{
    public class BusinessHelper
    {
        // 营业执照识别
        public static BusinessResult BusinessLicense(string filepath)
        {
            string token = AccessToken.GetToken(); //"[调用鉴权接口获取的token]";
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=" + token;
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = getFileBase64(filepath);// getFileBase64("[本地图片文件]");
            String str = "image=" + HttpUtility.UrlEncode(base64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
            string result = reader.ReadToEnd();
            //Console.WriteLine("营业执照识别:");
            //Console.WriteLine(result);
            var dto = JsonConvert.DeserializeObject<BusinessResult>(result);
            File.Delete(filepath);
            return dto;
        }

        // 表格文字识别(异步接口)
        public static string ConvertImg2Excel(string filepath, bool getResult = false, string request_id = "", string result_type = "excel")
        {
            var str = Img2ExcelRquest(filepath, getResult, request_id, result_type);
            //1.发出请求
            Img2Excel dto = JsonConvert.DeserializeObject<Img2Excel>(str);

            //2.根据返回的ID获得Excel
            var str2 = Img2ExcelRquest("", true, dto.result[0].request_id, "excel");
            var dto2 = JsonConvert.DeserializeObject<Img2ExcelResult>(str2);

            while (dto2.result.percent < 100)
            {
                System.Threading.Thread.Sleep(1000);
                str2 = Img2ExcelRquest("", true, dto2.result.request_id, "excel");
                dto2 = JsonConvert.DeserializeObject<Img2ExcelResult>(str2);
            }

            File.Delete(filepath);
            return dto2.result.result_data;
        }

        public static string Img2ExcelRquest(string filepath, bool getResult = false, string request_id = "", string result_type = "excel")
        {
            string token = AccessToken.GetToken(); //"[调用鉴权接口获取的token]";
            string host = "";
            if (getResult)
            {
                host = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result?access_token=" + token + "&request_id=" + request_id + "&result_type=" + result_type;
            }
            else
            {
                host = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request?access_token=" + token;
            }
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            if (!getResult)
            {
                // 图片的base64编码
                string base64 = getFileBase64(filepath);
                String str = "image=" + HttpUtility.UrlEncode(base64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
            string result = reader.ReadToEnd();
            Console.WriteLine("表格文字识别(异步接口):");
            Console.WriteLine(result);
            return result;
        }

        public static String getFileBase64(String fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
    }

    public class Img2Excel
    {
        public string log_id { get; set; }
        public List<Result> result { get; set; }
        public class Result
        {
            public string request_id { get; set; }
        }
    }


    public class Img2ExcelResult
    {
        public Result result { get; set; }
        public long log_id { get; set; }

        public class Result
        {
            public string result_data { get; set; }
            public string ret_msg { get; set; }
            public string request_id { get; set; }
            public int percent { get; set; }
            public int ret_code { get; set; }
        }
    }

    public class BusinessResult
    {
        public long log_id { get; set; }
        //public int direction { get; set; }
        public int words_result_num { get; set; }
        //public Dictionary<string, WordsReulst.Words> words_result { get; set; }
        public WordsReulst words_result { get; set; }

        public class WordsReulst
        {
            public Words 社会信用代码 { get; set; }
            public Words 组成形式 { get; set; }
            public Words 经营范围 { get; set; }
            public Words 成立日期 { get; set; }
            public Words 法人 { get; set; }
            public Words 注册资本 { get; set; }
            public Words 证件编号 { get; set; }
            public Words 地址 { get; set; }
            public Words 单位名称 { get; set; }
            public Words 有效期 { get; set; }
            public Words 类型 { get; set; }

            public class Words
            {
                public string words { get; set; }
                public Location location { get; set; }

                public class Location
                {
                    public int left { get; set; }
                    public int top { get; set; }
                    public int width { get; set; }
                    public int height { get; set; }
                }
            }
        }
    }

    public static class AccessToken
    {
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        //public static String TOKEN = "24.22dfcc6968857803b1569c78353e1dcd.2592000.1618026755.282335-23779080";
        public static string baidu_api_token = "baidu_api_token";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "b5XVjDK0qKixcODC391lXXe2";
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "oNccvtcTDFHK4gW4gKdncNpDwLnEy2YK";

        public static AccessTokenResult getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
            paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            //Console.WriteLine(result);

            var dto = JsonConvert.DeserializeObject<AccessTokenResult>(result);

            return dto;
        }

        public static string GetToken()
        {
            string TOKEN = "";
            Cache cache = new Cache();
            if (cache.Get(baidu_api_token) == null)
            {
                var token = getAccessToken();
                if (string.IsNullOrWhiteSpace(token.error))
                {
                    TOKEN = token.access_token;
                    cache.Insert(baidu_api_token, TOKEN, null, DateTime.Now.AddSeconds(token.expires_in).AddDays(-1), Cache.NoSlidingExpiration);   //token有效期为一个月，提前一天过期后系统会重新获得token
                }
                else
                {
                    throw new Exception("baidu.api interface error msg:" + token.error_description);
                }
            }
            else
            {
                TOKEN = (string)cache.Get(baidu_api_token);
            }
            return TOKEN;
        }
    }
    public class AccessTokenResult
    {
        public string refresh_token { get; set; }
        public int expires_in { get; set; }
        public string scope { get; set; }
        public string session_key { get; set; }
        public string access_token { get; set; }
        public string session_secret { get; set; }

        public string error { get; set; }
        public string error_description { get; set; }

    }

}
